package com.tensuqare.user.service;

import com.tensuqare.user.dao.UserDao;
import com.tensuqare.user.pojo.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private BCryptPasswordEncoder encoder;


    /**
     * 更新粉丝数
     */

    public void incFanscount(String userid, int x){
        userDao.incFanscount(userid,x);
    }

    /**
     * 更新关注数
     */
    public void incFollowcount(String userid, int x){
        userDao.incFollowcount(userid,x);
    }

    public void sendsms(String mobile) {
        //生成验证码（6位）
        int max= 999999;
        int min = 100000;
        Random r = new Random();
        int code = r.nextInt(max);
        if(code<min){
            code += min;
        }
        //保存验证码到redis
        redisTemplate.opsForValue().set(mobile,code+"",5, TimeUnit.MINUTES);
        //把验证码添加到队列中
        Map map = new HashMap();
        map.put("mobile", mobile);
        map.put("code", code+"");
        rabbitTemplate.convertAndSend("msg",map);
    }

    public void register(User user) {
        user.setId(idWorker.nextId()+"");
        user.setFollowcount(0);//关注数
        user.setFanscount(0);//粉丝数
        user.setOnline(0L);//在线时长
        user.setRegdate(new Date());//注册日期
        user.setUpdatedate(new Date());//更新日期
        user.setLastdate(new Date());//最后登陆日期
        String encodePassword = encoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        userDao.save(user);
    }

    public User finByMobileAndPassword(String mobile, String password) {
        User user = userDao.findByMobile(mobile);
        if (user != null && encoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }

    public void delete(String userId) {
        userDao.deleteById(userId);
    }
}
